<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >{{$t('add')}}</el-button>
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="tableRadio == null"
          @click="handleUpdate"
        >{{$t('edit')}}</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="tableRadio == null"
          @click="handleDelete"
        >{{$t('delete')}}</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="dataList">
      <el-table-column width="30px">
        <template slot-scope="scope">
          <el-radio v-model="tableRadio" :label="scope.row">
            <i></i>
          </el-radio>
        </template>
      </el-table-column>
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="类型Id" align="center" prop="typeId" width="280" />
      <el-table-column label="分类名称" align="center" prop="typeName" width="200" />
      <el-table-column label="语言类型" align="center" prop="language" width="300" />
      <el-table-column label="内容" align="center" prop="content" width="300">
        <template slot-scope="scope">
          <div v-html="scope.row.content"></div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改平台参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <el-row>
          <el-form-item :span="12" label="分类名称" prop="typeName">
            <div style="display: flex;">
              <el-input
                v-model="typeName"
                @input="handleInput"
                placeholder="请输入分类名称"
                style="width: 200px;margin-right: 12px;"
              ></el-input>
              <el-select
                v-model="form.typeName"
                @change="handleType"
                placeholder="请选择分类名称"
                style="width: 200px;"
              >
                <el-option
                  v-for="option in typeData"
                  :key="option.typeId"
                  :label="option.typeName"
                  :value="option.typeId"
                ></el-option>
              </el-select>
              <span
                style="color: rgb(154, 154, 154);margin-top: 6px;font-size: 12px;"
              >（分类名称，可以输入或者查询）</span>
            </div>
          </el-form-item>
          <el-form-item label="语言类型" prop="language">
            <dict-select
              :options="dict.type.national_language_code"
              v-model="form.language"
              placeholder="请选择字段分组"
            />
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <editor v-model="form.content" placeholder="请输入内容" :height="400" />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{$t('ok')}}</el-button>
        <el-button @click="cancel">{{$t('cancel')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTypeAll,
  getTypeDel,
  sysLanguageTextAdd,
  sysLanguageTextQuery,
  sysLanguageTextUpdate
} from '@/api/Instructions/Instructions'
import DictSelect from '@/components/DictSelect/index.vue'

export default {
  name: "PlatformConfig",
  components: { DictSelect },
  dicts: ['national_language_code'],
  data () {
    return {
      //字典数据
      typeData: [{ value: 'option1', label: '选项1' },
      { value: 'option2', label: '选项2' }],

      languageData: [{ name: 'zh-CN', type: 1, }, { name: 'en-US', type: 2 }],
      // 遮罩层
      loading: true,
      // 选中数组
      tableRadio: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台参数配置表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        groupId: null,
      },
      // 表单参数
      form: {},
      typeName: null,
      // 表单校验
      rules: {
        title: [
          { required: true, message: "字段名称不能为空", trigger: "blur" }
        ],
        key: [
          { required: true, message: "字段Key不能为空", trigger: "blur" }
        ],
        groupId: [
          { required: true, message: "字段分组不能为空", trigger: "change" }
        ],
        type: [
          { required: true, message: "字段类型不能为空", trigger: "change" }
        ],
        dictType: [
          { required: true, message: "字典类型不能为空", trigger: "change" }
        ]
      },
      countryType: [],
    }
  },
  created () {
    this.getCountryType()
    setTimeout(() => {
      this.getList()
    }, 500)

  },
  methods: {
    showHtml (str) {
      return str
        .replace(str ? /&(?!#?\w+;)/g : /&/g, '&amp;')
        .replace(/&lt;/g, "<")
        .replace(/&gt;/g, ">")
        .replace(/&quot;/g, "\"")
        .replace(/&#39;/g, "\'")
        .replace(/&amp;nbsp;/g, '\u3000')
    },
    getCountryType () {
      this.getDicts('national_language_code').then((res) => {
        console.log(res)
        this.countryType = res.data
      })
    },
    // // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.id)
    //   this.single = selection.length != 1
    //   this.multiple = !selection.length
    // },
    /** 查询平台参数配置列表 */
    getList () {
      this.loading = true
      this.tableRadio = null
      sysLanguageTextQuery(this.queryParams).then(response => {
        this.dataList = response.data.records || []
        this.total = response.data.total || 0
        this.dataList.map((item) => {
          this.countryType.map((ite) => {
            if (item.language == ite.dictValue) {
              item.language = ite.dictLabel
            }
          })
        })
        this.loading = false
      })
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        typeId: null,
        typeName: null,
        language: null,
        content: null,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    queryType () {
      getTypeAll().then(response => {
        console.log('response', response)
        this.typeData = response.data
      })
    },

    /** 新增按钮操作 */
    handleAdd () {
      this.typeName = null
      this.reset()
      this.queryType()
      this.open = true
      this.title = "添加平台参数配置"
    },
    /** 修改按钮操作 */
    handleUpdate () {
      this.reset()
      this.queryType()
      this.form = {
        ...this.tableRadio,
      }
      this.typeName = this.form.typeName
      this.open = true
      this.title = "修改平台参数配置"
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.typeName) this.form.typeName = this.typeName
          if (this.form.id != undefined) {
            sysLanguageTextUpdate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            sysLanguageTextAdd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      this.$modal.confirm(this.$t('delete-or-not')).then(() => {
        return getTypeDel(this.tableRadio.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess(this.$t('delete-success'))
      }).catch(() => {
      })
    },
    // 类型事件
    handleType (e) {
      let obj = this.typeData.find(item => item.typeId === e)
      this.typeName = obj.typeName
      this.form.typeId = obj.typeId
    },
    handleInput (e) {
      this.form.typeId = null
      this.form.typeName = e
    },
    renderDicts ({ dictType, value }) {
      if (this.dictsReady && value && value.length > 0) {
        value = value.split(',')
        if (this.dicts[dictType]) {
          let dict = [...this.dicts[dictType]]
          if (dict && dict.length) {
            let o = {}
            dict.forEach(i => {
              o[i.dictValue] = i.dictLabel
            })
            return value.map(v => o[v]).join(",")
          }
        }
      }
    },
    async getDictDatas (data) {
      if (data && data.length > 0) {
        let dicts = []
        for (const i of data) {
          if (!!i.dictType && !dicts.includes(i.dictType)) {
            dicts.push(i.dictType)
            this.dicts[i.dictType] = (await this.getDicts(i.dictType)).data
          }
        }
        this.dictsReady = true
      }
    }
  }
};
</script>
